package com.ftg.learn.hashiyou.service;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author 布衣
 */
@Service
public class BigWorkService {

    /**
     * 修改Word文档中的表格
     *
     * @param filePath Word文档的路径
     * @throws IOException 如果发生I/O错误
     */
    public void modifyWordTable(String filePath) throws IOException {
        try (XWPFDocument document = new XWPFDocument(Files.newInputStream(Paths.get(filePath)))) {
            // 假设我们要修改第一个表格
            XWPFTable table = document.getTableArray(1);

            //打分项
            XWPFTableRow row1 = table.getRow(3);

            //分段的打分
            int[] score1 = new int[]{25, 25, 15, 10, 15, 10};
            int sum = 0;
            for (int i = 0; i < score1.length; i++) {
                // 修改单元格内容（例如修改第一行第一列的内容）
                XWPFTableCell cell = row1.getCell(i);
                //清空单元格
                assert cell != null;
                cell.removeParagraph(0);
                cell.addParagraph();
                // 设置单元格1的文字
                XWPFParagraph paragraph1 = cell.getParagraphs().get(0);
                XWPFRun run1 = paragraph1.createRun();
                int s = (int) (score1[i] * 0.8) + (int) (Math.random() * (score1[i] * 0.2));
                run1.setText(s + "");
                run1.setColor("FF0000");
                sum += s;
            }

            //总分
            XWPFTableCell cellTotal = row1.getCell(score1.length);
            //清空单元格
            assert cellTotal != null;
            cellTotal.removeParagraph(0);
            cellTotal.addParagraph();
            XWPFParagraph totalParagraph = cellTotal.getParagraphs().get(0);
            XWPFRun totalRun = totalParagraph.createRun();
            totalRun.setText(Integer.toString(sum));
            totalRun.setColor("FF0000");

            //老师签名行
            XWPFTableRow row = table.getRow(4);

            //签名
            XWPFTableCell cell5 = row.getCell(2);
            //清空单元格
            assert cell5 != null;
            cell5.removeParagraph(0);
            cell5.addParagraph();
            // 图片文件路径
            String imgFile = "/sign.png";
            try (InputStream imgStream = this.getClass().getResourceAsStream(imgFile)) {
                assert imgStream != null;
                byte[] bytes = IOUtils.toByteArray(imgStream);

                // 创建一个段落和Run用于插入图片
                XWPFParagraph paragraph = cell5.getParagraphs().get(0);
                XWPFRun run = paragraph.createRun();
                run.addPicture(new ByteArrayInputStream(bytes), XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(100), Units.toEMU(100));
            } catch (InvalidFormatException e) {
                throw new RuntimeException(e);
            }

            //根据sum 计算评语
            int lv = sum < 60 ? 9 : sum < 70 ? 8 : sum < 80 ? 7 : sum < 90 ? 6 : 5;
            //生成right号
            XWPFTableCell cell6 = table.getRow(lv).getCell(1);
            //清空单元格
            assert cell6 != null;
            cell6.removeParagraph(0);

            cell6.addParagraph();
            XWPFParagraph lvParagraph = cell6.getParagraphs().get(0);
            XWPFRun lvRun = lvParagraph.createRun();
            lvRun.setText("✔");
            lvRun.setColor("FF0000");

            // 保存文档
            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
            }


        }
    }

    /**
     * 检查并设置值
     *
     * @param files    路径
     * @param snoOld   学号
     * @param scoreOld 分数
     * @return true|false
     */
    public boolean checkAndSetValue(String files, String snoOld, String scoreOld) {
        //保存成绩方法
        File file = new File(files);
        file.setWritable(true);
        try (FileInputStream fileIn = new FileInputStream(file);
             Workbook workbook = new XSSFWorkbook(fileIn)) { // 打开工作簿

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            for (int i = 4; i < sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i); // 获取第一行
                if (row == null) {
                    continue;
                }
                Cell sno = row.getCell(1); // 获取第一列的单元格
                System.out.println(sno.getStringCellValue()+"=="+snoOld+"命中:=>"+sno.getStringCellValue().equals(snoOld.trim()));
                if (sno.getStringCellValue().equals(snoOld.trim())) {
                    // 在行中创建一个单元格（例如第0列）

                    Cell cell = row.createCell(8);
                    // 设置单元格的值
                    System.out.println("命中后的值 :=>"+scoreOld);
                    cell.setCellValue(scoreOld);
                    break;
                }
            }
            // 将修改后的工作簿写回到文件
            try (FileOutputStream fileOut = new FileOutputStream(files)) {
                workbook.write(fileOut);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    /**
     * 修改Word文档中的表格  files 要与打分表文件名一致
     *
     * @param filePath Word文档的路径
     * @param files    分数汇总表
     * @throws IOException
     */
    @SuppressWarnings("all")
    public void modifyWordTable(String filePath, String files) throws IOException {
        System.out.println("==>" + filePath.toString());
        try (
                FileInputStream fis = new FileInputStream(filePath);
                OPCPackage pkg = OPCPackage.open(fis);
                XWPFDocument document = new XWPFDocument(pkg)
        ) {
            // 假设我们要修改第一个表格
            XWPFTable table = document.getTableArray(1);

            //打分项
            XWPFTableRow row1 = table.getRow(3);

            //分段的打分
            int[] score1 = new int[]{25, 25, 15, 10, 15, 10};
            int sum = 0;
            for (int i = 0; i < score1.length; i++) {
                // 修改单元格内容（例如修改第一行第一列的内容）
                XWPFTableCell cell = row1.getCell(i);

                //清空单元格
                assert cell != null;
                cell.removeParagraph(0);
                cell.addParagraph();
                // 设置单元格1的文字
                XWPFParagraph paragraph1 = cell.getParagraphs().get(0);
                XWPFRun run1 = paragraph1.createRun();
                int s = (int) (score1[i] * 0.7) + (int) (Math.random() * (score1[i] * 0.3));
                run1.setText(s + "");
                run1.setColor("FF0000");
                sum += s;
            }

            //总分
            XWPFTableCell cellTotal = row1.getCell(score1.length);
            //清空单元格
            assert cellTotal != null;
            cellTotal.removeParagraph(0);
            cellTotal.addParagraph();
            XWPFParagraph totalParagraph = cellTotal.getParagraphs().get(0);
            XWPFRun totalRun = totalParagraph.createRun();
            totalRun.setText(Integer.toString(sum));
            totalRun.setColor("FF0000");

            //老师签名行
            XWPFTableRow row = table.getRow(4);

            //签名
            XWPFTableCell cell5 = row.getCell(2);
            //清空单元格
            assert cell5 != null;
            cell5.removeParagraph(0);
            cell5.addParagraph();
            // 图片文件路径
            String imgFile = "/sign.png";
            try (InputStream imgStream = this.getClass().getResourceAsStream(imgFile)) {
                assert imgStream != null;
                byte[] bytes = IOUtils.toByteArray(imgStream);

                // 创建一个段落和Run用于插入图片
                XWPFParagraph paragraph = cell5.getParagraphs().get(0);
                XWPFRun run = paragraph.createRun();
                run.addPicture(new ByteArrayInputStream(bytes), XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(100), Units.toEMU(100));
            } catch (InvalidFormatException e) {
                throw new RuntimeException(e);
            }

            //根据sum 计算评语
            int lv = sum < 60 ? 9 : sum < 70 ? 8 : sum < 80 ? 7 : sum < 90 ? 6 : 5;
            //生成right号
            XWPFTableCell cell6 = table.getRow(lv).getCell(1);
            //清空单元格
            assert cell6 != null;
            cell6.removeParagraph(0);

            cell6.addParagraph();
            XWPFParagraph lvParagraph = cell6.getParagraphs().get(0);
            XWPFRun lvRun = lvParagraph.createRun();
            lvRun.setText("✔");
            lvRun.setColor("FF0000");


            // 请取第一个表格里面的学号
            XWPFTable table0 = document.getTableArray(0);

            XWPFTableRow rowSno = table0.getRow(3);

            XWPFTableCell cellSno = rowSno.getCell(1);
            //            学号
            String sno = cellSno.getText().trim();
            //保存分数到别一个文件夹
            this.checkAndSetValue(files, sno, Integer.toString(sum));

            // 保存文档
            try (FileOutputStream out = new FileOutputStream(filePath)) {
                document.write(out);
            }


        } catch (InvalidFormatException ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * 批量修改文件
     *
     * @param filePath 文件路径
     */
    @SuppressWarnings("all")
    public void readFile(String filePath) throws IOException {
        assert filePath != null;
        File file = new File(filePath);
        File[] files = file.listFiles();
        assert files != null;
        for (File f : files) {
            f.setWritable(true);
            this.modifyWordTable(f.getPath());
        }

    }

    public void readFileTotal(String filePath, String totalFile) throws IOException {
        assert filePath != null;
        File file = new File(filePath);
        File[] files = file.listFiles();
        assert files != null;
        for (File f : files) {
            f.setWritable(true);
            this.modifyWordTable(f.getPath(), totalFile);
        }

    }

}

